import Taro, {Component, Config} from '@tarojs/taro'
import {View, ScrollView} from '@tarojs/components'
import './index.less'
import {
  AtActivityIndicator,
  AtToast,
  AtButton,
  AtCard,
  AtList,
  AtListItem,
  AtMessage,
  AtIcon,
} from "taro-ui";
import {inject, observer} from "@tarojs/mobx";

@inject('locationStore')
@inject('userInfoStore')

@observer
export default class Detail extends Component<any, any> {
  constructor(props) {
    super(props)
    this.state = {
      paymentMethod: '1',
      orderLoading: true,
      totalPrice: 0,
      payLoading: false,
      toast: {
        isOpened: false,
        text: '',
        status: ''
      },
      note: '',
    }
  }

  componentWillMount() {
    const {shopId, locationId} = this.props.locationStore.location
    const shoppingCarList = JSON.parse(this.$router.params.shoppingCarList || "[]")
    const note = this.$router.params.note || ""
    const peopleSum = this.$router.params.peopleSum || ""
    if (shoppingCarList.length > 0) {
      Taro.request({
        url: `${process.env.remoteUrl}/order`,
        method: 'POST',
        data: {
          orderDetails: shoppingCarList.map(v => {
            return {
              foodDetail: {id: v.id, price: v.price || 100},
              number: v.number,
            }
          }),
          shopId,
          locationId,
          note,
          peopleSum
        }
      }).then(({data: res}) => {
        if (res.code == 200) {

        } else if (res.code == 500) {
          Taro.atMessage({
            'message': '查询订单出错',
            'type': 'error',
          })
          return
        } else {
          Taro.atMessage({
            'message': '网络不可用',
            'type': 'error',
          })
          return
        }
        //查询所有订单
        Taro.request({
          url: `${process.env.remoteUrl}/order?shopId=${shopId}&locationId=${locationId}`,
          method: 'GET'
        }).then(({data: res}) => {
          if (res.code == 200) {
            let totalPrice = 0
            res.data.forEach(v => {
              totalPrice = totalPrice + v.sum
            })
            this.setState({
              shoppingCarList: res.data,
              totalPrice: totalPrice
            })
          } else if (res.code == 500) {
            Taro.atMessage({
              'message': '查询订单出错',
              'type': 'error',
            })
          } else {
            Taro.atMessage({
              'message': '网络不可用',
              'type': 'error',
            })
          }
          this.setState({
            orderLoading: false,
          })
        })

      })
    } else {
      //查询所有订单
      Taro.request({
        url: `${process.env.remoteUrl}/order?shopId=${shopId}&locationId=${locationId}`,
        method: 'GET'
      }).then(({data: res}) => {
        if (res.code == 200) {
          let totalPrice = 0
          res.data.forEach(v => {
            totalPrice = totalPrice + v.sum
          })
          this.setState({
            shoppingCarList: res.data,
            totalPrice: totalPrice
          })
        } else if (res.code == 500) {
          Taro.atMessage({
            'message': '查询订单出错',
            'type': 'error',
          })
          return
        } else {
          Taro.atMessage({
            'message': '网络不可用',
            'type': 'error',
          })
          return
        }
        this.setState({
          orderLoading: false,
        })
      })
    }
  }

  config: Config = {
    navigationBarTitleText: '订单'
  }

  render() {
    return (
      <View style={{backgroundColor: '#b2b9d6'}}>
        <AtMessage/>
        <AtActivityIndicator isOpened={this.state.orderLoading}
                             size={48} content='加载中...'
                             color='green'
                             mode='center'/>
        <AtToast isOpened={this.state.toast.isOpened} text={this.state.toast.text}
                 status={this.state.toast.status} duration={1000}/>

        {
          !this.state.orderLoading &&
          <ScrollView style={{paddingBottom: '20px'}}>
            <View style={{height: '80px', textAlign: 'center', padding: 'auto'}}>
              <View style={{lineHeight: '80px', fontWeight: 'bold', fontSize: '18px',}}>
                ￥{this.state.totalPrice}
              </View>
            </View>

            {
              this.state.shoppingCarList.map(k => {
                return <View style={{marginTop: '8px'}}>
                  <AtCard
                    note={'备注：' + k.note}
                    title={this.props.locationStore.location.shop ?
                      this.props.locationStore.location.shop.name : ''}>
                    <AtList>
                      {k.orderDetails.map(v => {
                        return <AtListItem
                          title={v.foodDetail.name}
                          extraText={`￥${v.foodDetail.price * v.number}`}
                          note={`￥${v.foodDetail.price || 100} × ${v.number}`}
                          thumb={v.foodDetail.img}/>
                      })}
                    </AtList>
                  </AtCard>
                </View>
              })
            }

            {
              this.state.shoppingCarList.length === 0 ?
                <View>
                  <View className='at-row at-row__justify--center'>
                    <AtIcon value='close-circle' size='80' color='gray'/>
                  </View>
                  <View className='at-row at-row__justify--center' style={{marginTop: '20px'}}>暂无订单</View>
                </View> :
                <View>

                  <AtButton type='secondary' size='normal'
                            circle customStyle={{margin: '20px 10px'}}
                            onClick={() => {
                              Taro.navigateBack()
                            }}>
                    我要加菜
                  </AtButton>

                  <AtButton type='primary' size='normal'
                            loading={this.state.payLoading}
                            circle customStyle={{margin: '0 10px'}}
                            onClick={() => {
                              this.setState({
                                payLoading: true
                              })
                              const openId = this.props.userInfoStore.get('openId')
                              if (openId) {
                                const orderIds = this.state.shoppingCarList.map(k => k.id)
                                console.log('orderIds', orderIds);
                                Taro.request({
                                  url: `${process.env.remoteUrl}/wx/create_order?shopId=${this.props.locationStore.location.shopId}`,
                                  method: 'POST',
                                  data: {
                                    openid: openId,
                                    //FIXME
                                    attach: JSON.stringify({
                                      totalFee: this.state.totalPrice,
                                      orderIds: orderIds
                                    }),
                                    note: this.state.note
                                  }
                                }).then(({data: res}) => {
                                  this.setState({
                                    payLoading: false
                                  })
                                  Taro.requestPayment({
                                    timeStamp: res.data.timeStamp,
                                    nonceStr: res.data.nonceStr,
                                    package: res.data.packageValue,
                                    signType: res.data.signType,
                                    paySign: res.data.paySign,
                                    success: () => {
                                      this.setState({
                                        toast: {
                                          isOpened: true,
                                          text: '支付成功',
                                          status: 'success'
                                        }
                                      })
                                      Taro.navigateBack()
                                      Taro.clearStorage()
                                    },
                                    fail: () => {
                                      this.setState({
                                        toast: {
                                          isOpened: true,
                                          text: '支付失败',
                                          status: 'error'
                                        }
                                      })
                                    }
                                  })
                                }).finally(() => {
                                })
                              }
                            }
                            }>去买单
                  </AtButton>
                </View>
            }

          </ScrollView>
        }
      </View>

    )
  }
}

